<script lang="ts" setup>
import type { DataType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { AuthenticationQrCodeLogin, Page, useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';
// 引入组件

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getQrUuid,
  getThirdPartyUsers,
  postCheckQrUuid,
} from '#/api/plugin/wechat';
import Icon from '#/components/Icons';

defineOptions({
  name: 'PluginWechatAdminIndex',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
// 去除'列表'两个字
const viewTitle = routeMeta.title.replace('列表', '');
const qrcodeText = ref('');
const qruuid = ref('');
let interTimer: any = null;
const loading = ref(false);
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'id', title: '编号' },
    { field: 'user_login', title: '绑定账号' },
    { field: 'nickname', title: '昵称' },
    {
      field: 'openid',
      title: 'openid',
    },
    { field: 'avatar', title: '头像', cellRender: { name: 'CellAvatar' } },
    {
      field: 'create_time',
      title: '首次登录时间',
      formatter: 'formatShortDateTime',
    },
    { field: 'last_login_ip', title: '最后登录IP' },
    {
      field: 'last_login_time',
      title: '最后登录时间',
      formatter: 'formatShortDateTime',
    },
    { field: 'login_times', title: '登录次数' },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const { data } = await getThirdPartyUsers({
          page: page.currentPage,
          limit: page.pageSize,
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});
const [Modal, modalApi] = useVbenModal({
  footer: false,
  fullscreen: false,
  fullscreenButton: false,
  closeOnClickModal: false,
  onClosed() {
    if (interTimer) {
      clearInterval(interTimer);
    }
  },
});

const handleCloseDialog = () => {
  if (interTimer) {
    clearInterval(interTimer);
  }
  loading.value = false;
  qruuid.value = '';
  modalApi.close();
};
let num = 0;
const handleCheckQrUuid = async () => {
  num++;
  try {
    if (num >= 180 && interTimer) {
      handleCloseDialog();
      return;
    }
    const {
      data: { status },
    } = await postCheckQrUuid({
      q: qruuid.value,
      t: 'bind',
    });
    loading.value = status !== -1;
    if (status === 3) {
      message.success('绑定成功...');
      handleCloseDialog();
      GridApi.query();
    }
    if (status === -2) {
      handleCloseDialog();
      message.error('绑定失败！管理员账户已绑定。');
    }
  } catch {
    handleCloseDialog();
  }
};

const openModal = async () => {
  await getQrUuid().then((res) => {
    qruuid.value = res.data.qruuid;
    qrcodeText.value = res.data.url;
  });
  modalApi.open();
  num = 0;
  interTimer = setInterval(() => {
    handleCheckQrUuid();
  }, 1500);
};
</script>

<template>
  <Page auto-content-height>
    <Modal title="扫描二维码绑定微信">
      <AuthenticationQrCodeLogin
        :loading="loading"
        :text="qrcodeText"
        login-path=""
      >
        <template #title>
          <span></span>
        </template>
        <template #subTitle>
          <p class="text-center">使用微信扫码绑定管理员</p>
        </template>
      </AuthenticationQrCodeLogin>
    </Modal>
    <Grid :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openModal">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增{{ viewTitle }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
.qrcode-box {
  position: relative;
  width: 200px;
  height: 230px;
  padding-bottom: 20px;
  margin: 0 auto;
  text-align: center;
}

.qrcode-msg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgb(255 255 255 / 95%);
}

.msg-title {
  margin-top: 15px;
  font-size: 18px;
}

.msg-sub {
  font-size: 20px;
}
</style>
